<?php
include_once "com/code/Model.php";

class VideoSeacrhEngineModel extends Model {
	
	public function __construct() {
		parent::__construct();
	}

	public function __destruct() {
		parent::__destruct();
	}
	
	public function search($keywords) {
		$connection = mysql_connect("localhost", "root", "3lm4rc3l0");
		mysql_set_charset('utf8',$connection);
		mysql_select_db("visual", $connection);

		$keywords = trim($keywords);
		$keywords = mysql_real_escape_string($keywords, $connection);
		// escaping % and _ characters so they can be used in the next query, mysql_real_escape_string does not escape them
		$keywords = str_replace('%', '\\%', $keywords); // escaping % character
		$keywords = str_replace('_', '\\_', $keywords); // escaping _ character

		preg_replace('/\s+/i', ' ', $keywords);
		$keywordArray = explode(' ', $keywords);

		$query =  " SELECT * ";
		$query .= " FROM Video ";
		$query .= " WHERE 1=2 ";
		for($i=0 ; $i<count($keywordArray) ; $i++) {
			$query .= " OR Video.title LIKE '%".$keywordArray[$i]."%' ";
			$query .= " OR Video.description LIKE '%".$keywordArray[$i]."%' ";
		}
		$query .= " ORDER BY Video.title;";
		
		$result = mysql_query($query, $connection) or die(mysql_error());
		
		$beans = array();
		while ($obj = mysql_fetch_object($result)) {
			$beans[] = $obj;
		}

		mysql_free_result($result);
		mysql_close($connection);
		
		return $beans;
	}
}
?>